<template>
  <view class="scrap-add-container">
    
    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 报废单号 -->
      <view class="form-item">
        <view class="item-label required">报废单号</view>
        <view class="item-value readonly">{{ isEdit ? formData.scrapCode : '系统自动生成' }}</view>
      </view>
      
      <!-- 报废单名称 -->
      <view class="form-item">
        <view class="item-label">报废单名称</view>
        <input class="item-input" type="text" v-model="formData.scrapName" placeholder="请输入报废单名称" />
      </view>
      
      <!-- 报废人 -->
      <view class="form-item" @click="showUserPicker = true">
        <view class="item-label required">报废人</view>
        <view class="item-value picker">
          <text>{{ formData.scrapUserName || '请选择' }}</text>
          <u-icon name="arrow-right" size="28rpx" color="#999"></u-icon>
        </view>
      </view>
      
      <!-- 报废原因 -->
      <view class="form-item" @click="showReasonPicker = true">
        <view class="item-label required">报废原因</view>
        <view class="item-value picker">
          <text>{{ formData.scrapReasonName || '请选择' }}</text>
          <u-icon name="arrow-right" size="28rpx" color="#999"></u-icon>
        </view>
      </view>
    </view>
    
    <!-- 资产列表 -->
    <view class="assets-section">
      <view class="section-header">
        <view class="section-title">资产列表</view>
        <view class="section-count">共计: {{ selectedAssets.length }}</view>
      </view>
      
      <!-- 资产列表内容 -->
      <view class="assets-list">
        <template v-if="selectedAssets.length > 0">
          <view class="asset-item" v-for="(item, index) in selectedAssets" :key="index">
            <view class="asset-image">
              <image :src="item.image ? `${BASE_URL}/File/GetImage?fileId=${item.image}` : '/static/placeholder.png'"  mode="aspectFill"></image>
            </view>
            <view class="asset-info">
              <view class="asset-name">{{ item.assetName }}</view>
              <view class="asset-detail">资产分类: {{ item.assetClassName }}</view>
              <view class="asset-detail">资产编码: {{ item.assetCode }}</view>
              <view class="asset-detail">规格型号: {{ item.specModel }}</view>
            </view>
            <view class="asset-action">
              <u-icon name="close" size="40rpx" color="#999" @click="removeAsset(index)"></u-icon>
            </view>
          </view>
        </template>
        <view class="empty-assets" v-else>
          <u-empty mode="data" text="暂无资产，请点击下方添加按钮添加资产"></u-empty>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer-buttons">
      <view class="btn-add" @click="goToSelectAssets">添加</view>
      <view class="btn-submit" @click="submitForm">提交</view>
    </view>
    
    <!-- 报废人选择器 -->
    <up-picker
      :show="showUserPicker"
      :columns="[userList]"
      keyName="text"
      @cancel="showUserPicker = false"
      @confirm="confirmUser"
      :closeOnClickOverlay="false"
    />
    
    <!-- 报废原因选择器 -->
    <up-picker
      :show="showReasonPicker"
      :columns="[reasonList]"
      keyName="text"
      @cancel="showReasonPicker = false"
      @confirm="confirmReason"
      :closeOnClickOverlay="false"
    />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import http, { BASE_URL } from "@/api/request";
import { generateUUID } from '@/utils';
import { t } from "@/locale/index.js"

// 是否是编辑模式
const isEdit = ref(false);

// 表单数据
const formData = ref({
  id: '',  // 添加id字段
  scrapCode: '系统自动生成',
  scrapName: '',
  scrapUser: '',
  scrapUserName: '',
  scrapReason: '',
  scrapReasonName: '',
  attachment: ''
});

// 选择的资产列表
const selectedAssets = ref([]);

// 选择器状态
const showUserPicker = ref(false);
const showReasonPicker = ref(false);

// 选择器数据
const userList = ref([]);
const reasonList = ref([]);
const pageParams = ref({
		scrapCode: '',
		mode: ''
	});

	// 页面加载时判断是否为审核模式
onLoad((options) => {
  // 保存页面参数
  pageParams.value = {
    scrapCode: options.scrapCode || '',
    mode: options.mode || ''
  };

  // 判断是否为审核模式
  if(pageParams && pageParams.value.scrapCode){
    isEdit.value = true;
    formData.value.scrapCode = options.scrapCode;
    // 加载报废单详情
    loadScrapDetail(options.scrapCode);
  }
  if(isEdit.value){
    uni.setNavigationBarTitle({
      title: t("assetScrapping.edit")
    });
  }else{
    uni.setNavigationBarTitle({
      title: t("assetScrapping.add")
    })
  }
  // 加载用户列表
  loadUserList();
  
  // 加载报废原因列表
  loadReasonList();
});

// 加载报废单详情
const loadScrapDetail = (scrapCode) => {
  uni.showLoading({
    title: '加载中...'
  });
  
  http.post('/api/module/Invoke', {
    pageCode: 'assetscrapping',
    params: {
      args: [
        {
          name: 'interfaceCode',
          value: 'assetscrapping.getAssetScrapOrderDetail'
        },
        {
          name: 'scrapCode',
          value: scrapCode
        }
      ]
    },
    methodName: 'getAssetScrapOrderDetail'
  }).then(res => {
    uni.hideLoading();
    
    if (res.isSuccess && res.result) {
      const { masterInfo, assetDetails } = res.result;
      
      // 填充表单数据
      formData.value = {
        id: masterInfo.id,
        scrapCode: masterInfo.scrapCode,
        scrapName: masterInfo.scrapName,
        scrapUser: masterInfo.scrapUser,
        scrapUserName: masterInfo.scrapUserName,
        scrapReason: masterInfo.scrapReason,
        scrapReasonName: masterInfo.scrapReasonName,
        remark: masterInfo.remark || '',
        scrapStatus: masterInfo.scrapStatus,
      };
      
      // 填充资产列表
      if (assetDetails && Array.isArray(assetDetails)) {
        selectedAssets.value = assetDetails.map(item => ({
          id: item.id,
          assetId: item.id,
          assetCode: item.assetCode,
          assetName: item.assetName,
          assetClassName: item.assetClassName,
          specModel: item.specModel,
          image: item.image
        }));
      }
    } else {
      uni.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.error('加载报废单详情失败:', err);
    uni.hideLoading();
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    });
  });
};

// 页面显示
onShow(() => {
  // 检查是否有从资产选择页面返回的数据
  uni.$once('assetSelected', (assets) => {
    handleSelectAssets(assets);
  });
});

// 加载用户列表
const loadUserList = () => {
  const data = {
    code: "Sys_GetUserNameById",
    filters: [],
    allColumnFilter: true,
    tableFilters: []
  };

  http.post("/api/module/GetViewTable", data).then((res) => {
    if (res.isSuccess && res.result && res.result.viewTable) {
      userList.value = res.result.viewTable.map(item => ({
        text: item.text,
        value: item.id
      }));
    }
  }).catch(err => {
    console.error('获取用户列表失败:', err);
    uni.showToast({
      title: '获取用户列表失败',
      icon: 'none'
    });
  });
};

// 加载报废原因列表
const loadReasonList = () => {
  const params = [{
    id: generateUUID(),
    service: "Module",
    method: "getBasicData",
    param: JSON.stringify({
      code: "base>scrap_reason",
      filters: []
    })
  }];

  http.post("/api/module/GetBatchResult", params).then((res) => {
    if (res.isSuccess && res.code && res.result) {
      const reasonData = res.result[0].response.data.data || [];
      reasonList.value = reasonData.map(item => ({
        text: item.text,
        value: item.value
      }));
    } else {
      console.error('获取报废原因列表失败:', res.error);
      uni.showToast({
        title: '获取报废原因列表失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.error('获取报废原因列表失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
};

// 确认用户选择
const confirmUser = (e) => {
  const selectedUser = e.value[0];
  formData.value.scrapUser = selectedUser.value;
  formData.value.scrapUserName = selectedUser.text;
  showUserPicker.value = false;
};

// 确认报废原因选择
const confirmReason = (e) => {
  const selectedReason = e.value[0];
  formData.value.scrapReason = selectedReason.value;
  formData.value.scrapReasonName = selectedReason.text;
  showReasonPicker.value = false;
};


// 跳转到选择资产页面
const goToSelectAssets = () => {
  // 跳转到资产选择页面
  uni.navigateTo({
    url: '/components/assetsAddList/index?type=scrap'
  });
};

// 处理选择资产页面返回的数据
const handleSelectAssets = (assets) => {
  console.log('选择的资产:', assets);
  if (Array.isArray(assets) && assets.length > 0) {
    if (!selectedAssets.value) selectedAssets.value = [];
    
    // 转换资产数据格式
    const formattedAssets = assets.map(asset => ({
      id: asset.id,
      assetId: asset.id,
      assetName: asset.asset_name,
      assetClassName: asset.asset_category,
      assetCode: asset.asset_code,
      specModel: asset.spec_model,
      image: asset.image ? asset.image.trim() : '/static/images/default-asset.png'
    }));
    
    // 合并选中的资产，避免重复
    const existingIds = selectedAssets.value.map(item => item.id);
    const newAssets = formattedAssets.filter(asset => !existingIds.includes(asset.id));

    selectedAssets.value = [...selectedAssets.value, ...newAssets];
  }
};

// 移除资产
const removeAsset = (index) => {
  selectedAssets.value.splice(index, 1);
};

// 提交表单
const submitForm = () => {
  // 表单验证
  if (!formData.value.scrapUser) {
    uni.showToast({
      title: '请选择报废人',
      icon: 'none'
    });
    return;
  }
  
  if (!formData.value.scrapReason) {
    uni.showToast({
      title: '请选择报废原因',
      icon: 'none'
    });
    return;
  }
  
  if (selectedAssets.value.length === 0) {
    uni.showToast({
      title: '请添加报废资产',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载中
  uni.showLoading({
    title: '提交中...'
  });

  // 构建DTO对象
  const assetScrapSaveDTO = {
    id : formData.value.id || '',
    scrap_code : formData.value.scrapCode || '',
    scrap_name: formData.value.scrapName || '',
    scrap_user: formData.value.scrapUser,
    scrap_reason: formData.value.scrapReason,
    remark: formData.value.remark || '',
    scrap_status: formData.value.scrapStatus,
    assetScrapDets: selectedAssets.value.map(asset => ({
      asset_code: asset.assetCode,
      remark: ''  // 资产备注
    }))
  };

  // 调用保存接口
  http.post('/api/module/Invoke', {
    pageCode: 'assetscrapping',
    params: {
      args: [
        {
          name: 'interfaceCode',
          value: 'assetscrapping.saveAssetScrapOrder'
        },
        {
          name: 'assetScrapSaveDTO',
          value: JSON.stringify(assetScrapSaveDTO)
        }
      ]
    },
    methodName: 'saveAssetScrapOrder'
  }).then(res => {
    uni.hideLoading();
    console.log('提交结果:', res);
    if (res.isSuccess) {
      uni.showToast({
        title: isEdit.value ? '保存成功' : '提交成功',
        icon: 'success'
      });
      
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.error || '提交失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.error('提交失败:', err);
    uni.hideLoading();
    uni.showToast({
      title: '提交失败',
      icon: 'none'
    });
  });
};
</script>

<style lang="scss" scoped>
.scrap-add-container {
  padding-bottom: 120rpx;
  background-color: #f5f5f5;
}


.form-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 20rpx;
  
  .form-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-label {
      width: 180rpx;
      font-size: 28rpx;
      color: #333;
      
      &.required::before {
        content: '*';
        color: #ff4d4f;
        margin-right: 4rpx;
      }
    }
    
    .item-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      
      &.readonly {
        color: #999;
      }
      
      &.picker {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
    
    .item-input {
      flex: 1;
      height: 60rpx;
      font-size: 28rpx;
    }
  }
}

.assets-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 20rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .section-count {
      font-size: 26rpx;
      color: #666;
    }
  }
  
  .assets-list {
    .empty-assets {
      padding: 60rpx 0;
    }
    
    .asset-item {
      display: flex;
      padding: 20rpx 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .asset-image {
        width: 120rpx;
        height: 120rpx;
        margin-right: 20rpx;
        
        image {
          width: 100%;
          height: 100%;
          border-radius: 8rpx;
        }
      }
      
      .asset-info {
        flex: 1;
        
        .asset-name {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .asset-detail {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 6rpx;
        }
      }
      
      .asset-action {
        display: flex;
        align-items: center;
        padding: 0 10rpx;
      }
    }
  }
}

.footer-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 100rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .btn-add, .btn-submit {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .btn-add {
    background-color: #509EFF;
    color: #fff;
  }
  
  .btn-submit {
    background-color: #509EFF;
    color: #fff;
  }
}
</style>